package com.banciyuan.bcywebview.biz.main.newdiscover.index;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoreApi;
import com.banciyuan.bcywebview.api.DiscoverApi;
import com.banciyuan.bcywebview.api.TagApi;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.fragment.BaseContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.push.Item.BasePush;
import com.banciyuan.bcywebview.base.helper.push.Item.PushError;
import com.banciyuan.bcywebview.base.helper.push.PushFactory;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreashRecycleView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.biz.circles.discover.DiscoverCircleActivity;
import com.banciyuan.bcywebview.biz.main.banner.ViewBanner;
import com.banciyuan.bcywebview.biz.main.newdiscover.index.discoverholder.HeaderViewHolder;
import com.banciyuan.bcywebview.biz.main.newdiscover.ranklist.RankListActivity;
import com.banciyuan.bcywebview.biz.write.photoselecotor.util.CommonUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.AcgItem;
import de.greenrobot.daoexample.model.CategroyTag;
import de.greenrobot.daoexample.model.DiscoverBanner;
import de.greenrobot.daoexample.model.Timeline;

public class NewDiscoverFragment extends BaseContainerFragment implements View.OnClickListener {

    public static final int TAG = 1;
    private boolean loading = false;
    private boolean is_end = false;
    private int page = 1;

    private RequestQueue mQueue;
    private PullToRefreashRecycleView refreshView;
    private RecyclerView lv;
    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private DiscoverAdapter adapter;

    private List<Timeline> finalDiscoverChoice = new LinkedList<>();
    private List<DiscoverBanner> discoverBanners = new ArrayList<>();
    private List<AcgItem> acgItems = new ArrayList<>();
    private List<CategroyTag> categroyTags = new ArrayList<>();

    private List<String> timeLineKeys = new ArrayList<>();
    private HeaderViewHolder headerViewHolder;
    private boolean isWorkEnd;
    private boolean isTagEnd;

    private boolean hasRecommend;
    private boolean hasTopic;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.discover_layout, container, false);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        initData();
        initBanners();
        getWork();
        getTypeTag();
        return rootView;
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                if (!loading) {
                    mProgressbarHelper.onLoading();
                    loading = true;
                    page = 1;
                    initData();
                    initBanners();
                    getWork();
                    getTypeTag();
                }
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        headerViewHolder = new HeaderViewHolder(View.inflate(getActivity(), R.layout.discover_header, null));
        int height = (int) (CommonUtils.getWidthPixels(getActivity()) * 0.34);
        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
        headerViewHolder.pageBanner.setLayoutParams(rl);
        refreshView = (PullToRefreashRecycleView) rootview.findViewById(R.id.timeline_refresh_lv);
        lv = refreshView.getRefreshableView();

        adapter = new DiscoverAdapter(getActivity(), finalDiscoverChoice, headerViewHolder);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        lv.setLayoutManager(linearLayoutManager);
        lv.setAdapter(adapter);

        ImageLoader.getInstance().displayImage(getString(R.string.discover_rank_pic), headerViewHolder.ivRankingList);
        headerViewHolder.workLine.setOnClickListener(this);
        headerViewHolder.tagLine.setOnClickListener(this);
        headerViewHolder.ivRankingList.setOnClickListener(this);
    }

    @Override
    protected void initAction() {

        refreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                loading = false;
                is_end = false;
                hasRecommend = false;
                hasTopic = false;
                page = 1;
                timeLineKeys.clear();
                initBanners();
                initData();
                processTagCover();
                processWorkCover();
            }
        });

        lv.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onBottom() {
                if (!loading && !is_end) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
    }

    private void initBanners() {
        List<BcyPair> paramsList = new ArrayList<>();
        if (UserDataHelper.ifLogin(getActivity())) {
            paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        }
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + DiscoverApi.getBanners();
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                        Gson gson = new Gson();
                        JSONObject result = new JSONObject(s);
                        List<DiscoverBanner> banners = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<DiscoverBanner>>() {
                        }.getType());
                        popIllegalBannerData(banners);
                        setBannerUi(banners);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, getActivity(), params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void popIllegalBannerData(List<DiscoverBanner> banners) {
        List<DiscoverBanner> illegalBanners = new ArrayList<>();
        for (int i = 0; i < banners.size(); i++) {
            BasePush basePush = PushFactory.getPush(banners.get(i).getCode());
            if (basePush instanceof PushError) {
                illegalBanners.add(banners.get(i));
            }
        }
        banners.removeAll(illegalBanners);
    }

    private void setBannerUi(List<DiscoverBanner> banners) {
        discoverBanners.clear();
        discoverBanners.addAll(banners);
        if (null == getActivity())
            return;
        if (discoverBanners.size() > 0) {
            headerViewHolder.rlBanner.setVisibility(View.VISIBLE);
            headerViewHolder.pageBanner.setPages(new CBViewHolderCreator() {
                @Override
                public Object createHolder() {
                    return new ViewBanner();
                }
            }, discoverBanners)
                    .setPageIndicator(new int[]{R.drawable.shape_dot_unselected, R.drawable.shape_dot_selected});
        } else {
            headerViewHolder.rlBanner.setVisibility(View.GONE);
        }
    }

    private void getTypeTag() {
        String url = HttpUtils.BASE_URL + TagApi.getTypeTagCircle();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    try {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(response);
                        categroyTags = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<CategroyTag>>() {
                        }.getType());
                        processTagCover();
                        isTagEnd = true;
                        checkEnd();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam param = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        mQueue.add(param);
    }


    private void getWork() {
        String url = HttpUtils.BASE_URL + CoreApi.getworkHotWork();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        acgItems = gson.fromJson(result, new TypeToken<List<AcgItem>>() {
                        }.getType());
                        processWorkCover();
                        isWorkEnd = true;
                        checkEnd();
                    } catch (Exception e) {
                        e.printStackTrace();

                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam param = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        mQueue.add(param);
    }

    private void checkEnd() {
        if (isWorkEnd && isTagEnd) {
            headerViewHolder.header_container.setVisibility(View.VISIBLE);
        }
    }

    private void processWorkCover() {
        Collections.shuffle(acgItems);
        if (!acgItems.isEmpty()) {
            AcgItem acgItem = acgItems.get(0);
            if (acgItem != null) {
                ImageLoader.getInstance().displayImage(acgItem.getCover(), headerViewHolder.ivWorks);
                String names = "";
                for (int i = 0; i < acgItems.size(); i++) {
                    if (i < 3) {
                        names += acgItems.get(i).getReal_name() + "，";
                    }
                }
                if (!TextUtils.isEmpty(names)) {
                    headerViewHolder.workNames.setText(names.substring(0, names.length() - 1));
                }
            }
        }
    }

    private void processTagCover() {
        Collections.shuffle(categroyTags);
        if (!categroyTags.isEmpty()) {
            CategroyTag categroyTag = categroyTags.get(0);
            if (categroyTag != null && categroyTag.getTags_data() != null) {
                if (!TextUtils.isEmpty(categroyTag.getType_name())) {
                    headerViewHolder.tagType.setText(categroyTag.getType_name());
                }
                ImageLoader.getInstance().displayImage(categroyTag.getTags_data().get(0).getCover(), headerViewHolder.ivTags);
                String names = "";
                for (int i = 0; i < categroyTag.getTags_data().size(); i++) {
                    if (i < 3) {
                        names += categroyTag.getTags_data().get(i).getTag_name() + "，";
                    }
                }
                if (!TextUtils.isEmpty(names)) {
                    headerViewHolder.tagNames.setText(names.substring(0, names.length() - 1));
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (null != headerViewHolder.pageBanner) {
            headerViewHolder.pageBanner.startTurning(3000);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (null != headerViewHolder.pageBanner) {
            headerViewHolder.pageBanner.stopTurning();
        }
    }

    @Override
    public void selfUpdateData() {
        if (null != refreshView) {
            refreshView.setRefreshing();
            lv.scrollToPosition(0);
        }
    }

    @Override
    protected void initData() {
        loading = true;
        String url = HttpUtils.BASE_URL + DiscoverApi.getHotTimeline();
        List<BcyPair> paramsList = new ArrayList<>();
        if (UserDataHelper.ifLogin(getActivity())) {
            paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        }
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        LinkedList<Timeline> templist = TimelineFactory.createTimeline(jsonObject.getJSONArray(HttpUtils.UPLOAD_DATA));
                        TimelineFactory.popIllegalItemDiscover(templist);
                        TimelineFactory.removeDuplicate(templist, timeLineKeys);
                        findFirstItem(templist);
                        processAdapter(templist);
                    } catch (Exception e) {
                        e.printStackTrace();
                        onError();
                    }
                } else {
                    onError();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyError.printStackTrace();
                onError();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, getActivity(), params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
        refreshView.onRefreshComplete();
        mProgressbarHelper.onSuccess();
    }

    private void findFirstItem(List<Timeline> templist) {
        for (Timeline t : templist) {
            if (TimelineFactory.whichType(t) == TimelineFactory.TIMELINE_TYPE_TOPIC && !hasTopic) {
                t.setIsfirst(true);
                hasTopic = true;
            }
            if (StringUtil.notNullEqual("discover", t.getTl_type()) && !hasRecommend) {
                t.setIsfirst(true);
                hasRecommend = true;
            }
        }
    }

    private void onError() {
        if (page == 1) {
            mProgressbarHelper.onFailed();
        }
        refreshView.onRefreshComplete();
        loading = false;
    }

    private void processAdapter(List<Timeline> templist) {
        int start = finalDiscoverChoice.size() + 1;
        if (page == 1) {
            finalDiscoverChoice.clear();
        }
        finalDiscoverChoice.addAll(templist);
        if (null == adapter) {
            adapter = new DiscoverAdapter(getActivity(), finalDiscoverChoice, headerViewHolder);
            lv.setAdapter(adapter);
        } else {
            if (page == 1) {
                adapter.notifyDataSetChanged();
            } else {
                adapter.notifyItemRangeInserted(start + 1, templist.size());
            }
        }
        mProgressbarHelper.onSuccess();
        refreshView.onRefreshComplete();
        loading = false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_work_circle:
                gotoUtil.gotoAct(getActivity(), DiscoverCircleActivity.class, DiscoverCircleActivity.TYPE_WORK);
                break;
            case R.id.rl_tag_circle:
                gotoUtil.gotoAct(getActivity(), DiscoverCircleActivity.class, DiscoverCircleActivity.TYPE_TAG, headerViewHolder.tagType.getText().toString());
                break;
            case R.id.iv_ranking_list:
                gotoUtil.gotoAct(getActivity(), RankListActivity.class);
                break;
        }
    }
}
